package 多线程;

/**
 * 使用三个线程交替打印1，2，3
 * 思路： 使用synchronized关键字，保证线程安全，使用wait和notify方法，实现线程间的通信
 */
public class AlternatingPrint {

    private static final Object lock = new Object();
    private static int currentNumber = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(new PrintNumber(1));
        Thread t2 = new Thread(new PrintNumber(2));
        Thread t3 = new Thread(new PrintNumber(3));

        t1.start();
        t2.start();
        t3.start();
    }

    static class PrintNumber implements Runnable {
        private final int number;
        public PrintNumber(int number) {
            this.number = number;
        }
        @Override
        public void run() {
            while (true){
                synchronized (lock){
                    while (currentNumber != number){
                        try {
                            lock.wait();
                        } catch (InterruptedException  e) {
                            Thread.currentThread().interrupt();
                            System.out.println(Thread.currentThread().getName() + " was interrupted.");
                        }
                    }
                    System.out.print(number+" ");
                    if(number == 3){
                        currentNumber = 1;
                    }else {
                        currentNumber++ ;
                    }
                    lock.notifyAll();
                }
            }
        }
    }

}


